<template>
  <div id="app">
    <h2>商品清单如下：</h2>
    <div v-for="(item, index) in list" :key="index">{{item.shopName}} {{item.price}}元/份</div>
    <h2>请选择购买数量</h2>
    <div v-for="(item, index) in list" :key="index+'-2'">{{item.shopName}} <mid-com :num="item.count" :index="index" @chNum="chNum" /></div>
    <div>总价为: {{total}}</div>
  </div>
</template>

<script>
import MidCom from './components/mid-com'
export default {
  name: 'App',
  data () {
    return {
      list: [
        {
          shopName: '可比克薯片',
          price: 5.5,
          count: 0
        },
        {
          shopName: '草莓酱',
          price: 3.5,
          count: 0
        },
        {
          shopName: '红烧肉',
          price: 55,
          count: 0
        },
        {
          shopName: '方便面',
          price: 12,
          count: 0
        }
      ]
    }
  },
  components: {
    MidCom
  },
  methods: {
    chNum (num, index, type) {
      if (type === 'add') {
        this.list[index].count++
      }
      if (type === 'sub') {
        if (this.list[index].count > 0) {
          this.list[index].count--
        }
      }
    }
  },
  computed: {
    total () {
      return this.list.reduce((p, n) => p + n.price * n.count, 0).toFixed(2)
    }
  }
}
</script>

<style>

</style>
